﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace CommonLibrary.Utils
{

    public class CommonFtpTool
    {
        public static bool FtpUploadFile(string ftpAdress, string localFile, string user, string passwd, string localBasePath)
        {
            bool exeRs = false;
            string fileName = Path.GetFileName(localFile);
            string localDirPath = localFile.Replace(fileName, string.Empty);
            string relativePath = localDirPath.Replace(localBasePath, string.Empty).Replace(@"\", "/");
            if (relativePath.StartsWith("/"))
                relativePath = relativePath.Substring(1);
            try
            {
                string ftpFileDir = Path.Combine(ftpAdress, relativePath).Replace(@"\", "/");
                string ftpDir = FtpMakeDirectory(ftpAdress, relativePath, user, passwd);

                string ff = Path.Combine(ftpFileDir, fileName).Replace(@"\", "/");
                FtpWebRequest ftp = System.Net.FtpWebRequest.Create(ff) as FtpWebRequest;
                ftp.Credentials = new System.Net.NetworkCredential(user, passwd);
                ftp.KeepAlive = false;
                //指定文件传输的数据类型
                ftp.UseBinary = true;
                ftp.UsePassive = true;
                ftp.Method = WebRequestMethods.Ftp.UploadFile;
                using (FileStream fs = new FileStream(localFile, FileMode.Open))
                {
                    long fsLen = fs.Length;
                    byte[] buff = new byte[fsLen];
                    fs.Read(buff, 0, (int)fsLen);
                    using (Stream stream = ftp.GetRequestStream())
                    {
                        stream.Write(buff, 0, (int)fsLen);
                    }
                    fs.Close();
                }
                exeRs = true;
            }
            catch (Exception ex)
            {
                throw;//CommonLog.LogError(ex, $"Ftp备份({localFile})失败");
            }
            return exeRs;
        }

        /// <summary>
        /// 判断ftp服务器上该目录是否存在
        /// </summary>
        /// <param name="ftpPath">FTP路径目录/目录上的文件夹名称</param>
        /// <returns></returns>
        private static bool CheckFtpDirectoryExist(string ftpPath, string user, string passwd)
        {
            bool flag = true;
            try
            {
                //实例化FTP连接
                FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpPath);
                ftp.Credentials = new NetworkCredential(user, passwd);
                ftp.KeepAlive = false;
                ftp.Method = WebRequestMethods.Ftp.ListDirectory;
                using FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 创建文件夹  
        /// </summary>  
        /// <param name="ftpPath">FTP路径</param>  
        /// <param name="dirName">创建文件夹名称</param>  
        public static string FtpMakeDirectory(string ftpPath, string dirName, string user, string passwd)
        {
            string ftpDirPath = null;
            try
            {
                string[] subDirs = dirName.Split('/');
                foreach (string subDir in subDirs)
                {
                    if (string.IsNullOrWhiteSpace(subDir)) { continue; }

                    ftpPath = Path.Combine(ftpPath, subDir).Replace(@"\", "/");//(ftpPath + subDir + @"/").Trim();
                    if (!CheckFtpDirectoryExist(ftpPath, user, passwd))
                    {
                        //不存在，则创建此文件夹
                        FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(ftpPath);
                        reqFTP.KeepAlive = false;
                        reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                        reqFTP.UseBinary = true;
                        reqFTP.Credentials = new NetworkCredential(user, passwd);
                        using FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                        using Stream ftpStream = response.GetResponseStream();
                        ftpStream.Close();
                        response.Close();
                        ftpDirPath = ftpPath;
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return ftpDirPath;
        }

    }
}
